<template>
  <div>
    <template v-if="viewType==='list'">
      <CUpload v-show="comFileList.length<limit && uploadable" ref="CUpload" v-model="fileList" :limit="limit" :data="comData" :model-id="modelId" v-bind="$attrs" @template-success="templateSuccessHandle" />
      <slot name="tip">
        <div v-if="!!tip" class="tip">
          {{ tip }}
        </div>
      </slot>
      <ul class="c-file-list" :style="{width:width}">
        <li v-for="file in comFileList" :key="file.uid" class="c-file-list-item">
          <div v-if="file.status==='uploading'" class="progress">
            <el-progress :percentage="Math.floor(file.percentage)" :status="getStatus(file)" />
            <span>{{ getFileData(file).attachmentName }}</span>
          </div>
          <div v-else class="edit">
            <div class="file-name">
              <el-input v-show="file.editable" ref="elinput" v-model.trim="file.name" @change="v=>changeHandle(file, v)" @blur="editHandle(file)" />
              <span v-show="!file.editable">{{ getFileData(file).attachmentName }}</span>
            </div>
            <div class="option-box">
              <span
                v-show="editable"
                class="option-icon"
                @click="removeFile(file)"
              >
                <i class="el-icon-delete" />
              </span>
              <span
                v-show="editable"
                class="option-icon"
                @click="editHandle(file)"
              >
                <i class="el-icon-edit" />
              </span>
              <!-- 所有文件可直接下载 -->
              <span class="option-icon" @click="downAccessory(file)">
                <i class="el-icon-download" />
              </span>
              <span
                class="option-icon"
                @click="previewHandle(file)"
              >
                <i class="el-icon-zoom-in" />
              </span>
            </div>
          </div>
        </li>
      </ul>
    </template>
    <ul v-else class="c-img-list">
      <li v-for="file in comFileList" :key="file.uid" class="c-img-list-item">
        <div v-if="file.status==='uploading'" class="progress">
          <el-progress type="circle" :percentage="Math.floor(file.percentage)" :status="getStatus(file)" />
          <span>{{ getFileData(file).attachmentName }}</span>
        </div>
        <template v-else>
          <div class="image">
            <c-accessory width="150px" height="150px" :src="getFileData(file).attachmentUrl" :type="getFileData(file).typeName" />
            <div class="mask">
              <div>
                <div v-show="editable" class="item" @click.stop="removeFile(file)">删除</div>
                <div v-show="editable" class="item" @click.stop="editHandle(file)">编辑</div>
                <div class="item" @click.stop="downAccessory(file)">下载</div>
              </div>
            </div>
          </div>
          <div class="name">
            <el-input v-show="file.editable" ref="elinput" v-model.trim="file.name" @change="v=>changeHandle(file, v)" @blur="editHandle(file)" />
            <span v-show="!file.editable">{{ getFileData(file).attachmentName }}</span>
          </div>
        </template>
      </li>
      <li v-show="comFileList.length<limit && uploadable" class="c-img-list-item c-img-list-item-upload">
        <CUpload ref="CUpload" v-model="fileList" :limit="limit" :data="comData" :model-id="modelId" v-bind="$attrs" @template-success="templateSuccessHandle">
          <i slot="trigger" class="el-icon-plus avatar-uploader-icon" />
        </CUpload>
      </li>
    </ul>
    <el-button v-show="belongModel&&attachmentType" :loading="loading" size="mini" type="text" @click="downloadTemp">模板下载<i class="el-icon-download" /></el-button>

  </div>
</template>
<script>
import { configAttachmentTemplate } from '@/api/user'
import CUpload from './Upload'
import { otherFiltersItem } from '@/utils'

import { getShopAttachment, putShopAttachment, downloadFile } from '@/api/common'
export default {
  name: 'CFileList',
  components: {
    CUpload
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    width: {
      type: String,
      default: '800px'
    },
    viewType: {
      type: String,
      default: 'list'
    },
    limit: {// 文件上传限制个数
      type: Number,
      default: 200
    },
    modelId: {
      type: String,
      default: ''
    },
    data: {
      type: Array,
      default: () => []
    },
    uploadable: {
      type: Boolean,
      default: true
    },
    belongModel: {
      type: String,
      default: ''
    },
    attachmentType: {
      type: Boolean,
      default: true
    },
    editable: {
      type: Boolean,
      default: true
    },
    tip: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: [],
      templateData: [],
      // fileListData: [],
      rawFileListData: [],
      tempIds: [],
      loading: false
    }
  },
  computed: {
    fileListData() {
      return this.rawFileListData.filter(e => {
        const isNone = this.attachmentType === '' && this.belongModel === '' && this.id === '' && this.typeCode === ''
        return isNone || this.tempIds.includes(e.configAttachmentId)
      })
    },
    comData() {
      return [...this.data, ...this.fileListData]
    },
    comFileList() {
      return this.fileList.filter(e => ((e.response || {}).data || {}).dr !== 1)
    }
  },
  watch: {
    fileList: {
      handler(v) {
        this.$emit('input', v)
      }
    },
    modelId: {
      handler(v) {
        this.getShopAttachment()
      },
      immediate: true
    }
  },
  methods: {
    downloadTemp() {
      this.loading = true
      // 获取templatePage数据列表
      const data = new FormData()
      data.append('filtersRaw', JSON.stringify([otherFiltersItem('belongModel', this.belongModel, '=')]))

      configAttachmentTemplate(data).then(res => {
        if (res.success) {
          const temp = res.data.records.filter(v => v.attachmentType === this.attachmentType)
          if (temp.length > 0) {
            getShopAttachment(temp[0].id).then(res => {
              if (res.success === 1 && res.data.length > 0) {
                this.templateData = res.data
                this.templateData.forEach(item => {
                  let fileName = item.attachmentName
                  if (fileName.replace(/(.*)\.(\w+)$/g, '$2') !== item.typeName.replace(/\.(\w+)$/, '$1')) {
                    fileName = `${fileName}.${item.typeName.replace('.', '')}`
                  }
                  return downloadFile(item.attachmentUrl).then(res => {
                    const t = URL.createObjectURL(res)
                    const a = document.createElement('a')
                    a.href = t
                    a.download = fileName
                    a.click()
                    setTimeout(() => {
                      URL.revokeObjectURL(t)
                    }, 0)
                  })
                })
                setTimeout(() => {
                  this.loading = false
                }, 1000)
              } else {
                this.loading = false
                this.$message.warning('暂无模板可下载')
              }
            })
          }
        }
      })
    },
    // 获取模板成功
    templateSuccessHandle(tempData) {
      this.tempIds = tempData.map(e => e.id)
      // this.getShopAttachment(tempData)
    },
    // 根据modelId获取附件
    getShopAttachment() {
      if (this.modelId === '' || this.modelId === undefined) return
      // const tempIds = tempData.map(e => e.id)
      // const all = tempIds.length === 0
      getShopAttachment(this.modelId).then(res => {
        this.rawFileListData = res.data
        // this.fileListData = res.data.filter(e => {
        //   return all || tempIds.includes(e.configAttachmentId)
        // })
      })
    },
    getFileData(file) {
      return this.$refs.CUpload.getFileData(file)
    },
    getStatus(file) {
      let status = 'success'
      if (file.status === 'uploading') {
        status = undefined
      } else if (file.status === 'fail') {
        status = 'exception'
      }
      return status
    },
    downAccessory(row) {
      this.$refs.CUpload.downFile(row)
    },
    previewHandle(row) {
      this.$refs.CUpload.preview(row)
    },
    removeFile(row) {
      this.$refs.CUpload.removeFile(row)
    },
    editHandle(row) {
      this.$set(row, 'editable', !row.editable)
    },
    changeHandle(file, v) {
      if (v === '' || v === undefined) {
        this.$message.warning('文件名不能为空！')
        this.$set(file, 'name', file.response.data.attachmentName)
      // eslint-disable-next-line no-constant-condition
      } else if (file.flag === 'data' && false) { // 现在统一修改
        const name = file.response.data.attachmentName
        this.$set(file.response.data, 'attachmentName', v.trim())
        putShopAttachment(file.response.data).then(res => {
          this.$message.success('编辑保存文件名成功！')
        }).catch(() => {
          this.$set(file, 'name', name)
        })
      } else {
        this.$set(file.response.data, 'attachmentName', v.trim())
      }
    },
    clickHandle(file) {
      if (this.isImage(file)) return
      this.previewHandle(file)
    },
    isImage(file) {
      return /^\.jpe?g$|^\.png$|^\.gif$/.test(file.typeName)
    }
  }
}
</script>
<style lang="scss" scoped>
.c-file-list{
  list-style: none;
  padding: 0;
  margin: 0;
  .c-file-list-item{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    min-height: 30px;
    .progress{
      flex: 1 1 100%;
    }
    .edit{
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex: 0 0 100%;
      .file-name{
        flex: 0 0 60%;
      }
      .option-box{
        margin-left: 20px;
        flex: 0 0 100px;
        .option-icon{
          cursor: pointer;
        }
        .option-icon + .option-icon{
          margin-left: 10px;
        }
      }
    }
  }
  .c-file-list-item + .c-file-list-item{
    margin-top: 5px;
  }
}
.c-img-list{
  list-style: none;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
  .c-img-list-item{
    width: 150px;
    // height: 200px;
    margin-right: 10px;
    .progress{
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    .image {
      position: relative;
      height: 150px;
      width: 150px;
      .elImage{
        height: 150px;
        width: 150px;
      }
      .mask{
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 40px;
        background-color: rgba(3,3,3,0.6);
        display: none;
        &>div{
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          display: flex;
          & .item{
            flex: 1 1 auto;
            cursor: pointer;
            color: #fff;
            text-align: center;
            height: 40px;
            line-height: 40px;
          }
        }
      }
      &:hover .mask{
        display: block;
      }
    }
    .name{
      margin-top: 10px;
    }
  }
  // .c-img-list-item + .c-img-list-item{
  //   margin-left: 10px;
  // }
  .c-img-list-item-upload{
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
    // margin-left: 10px;
  }
}
  /deep/ .fail-text{
    width: 150px;
    height: 150px;
    text-align: center;
    border: 1px solid #d9d9d9;
    box-sizing: border-box;
    font-size: 28px;
    color: #8c939d;
    border-radius: 4px;
    line-height: 150px;
  }
  .tip{
    color: red !important;
    font-size: 14px;
    line-height: 30px;
  }
</style>
